package com.shop.loan.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
public class AMapUtil {

    @Value("${api.amap.key}")
    private String key;

    public String getInfoByLocation(String location) {
        if (!StringUtils.hasLength(location) || !location.contains(",")) {
            return null;
        }
        String apiUrl = "https://restapi.amap.com/v3/geocode/regeo?key=" + key + "&location=" + location;
        JSONObject jsonObject = new JSONObject();
        String result = HttpRequest.get(apiUrl)
                .execute().body();
        log.info("高德地图【getInfoByLocation】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if ("10000".trim().equals(resultJs.getString("infocode"))) {
            if (resultJs.containsKey("regeocode")) {
                return resultJs.getJSONObject("regeocode").getString("formatted_address");
            }
        }
        return null;
    }


}
